#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "chartdialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    setFixedSize ( 660, 460 );
    setWindowFlags(Qt::WindowCloseButtonHint|Qt::WindowMinimizeButtonHint);
    setWindowTitle(QStringLiteral("油井功图分析系统V1.0"));

    serialPort = new QSerialPort;
        foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
        {
            QSerialPort serial;
            serial.setPort(info);
            /*
            if(serial.open(QIODevice::ReadWrite))//能打开的串口放入列表
            {
                ui->combo_uart->addItem(serial.portName());
                serial.close();
            }
            */
            ui->combo_uart->addItem(serial.portName());//所有串口放入列表
        }

        ui->combo_baud->addItem("9600");
        ui->combo_baud->addItem("115200");

}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_pushButton_2_clicked()
{
    ChartDialog *CDlg;
    CDlg = new ChartDialog;
    CDlg->show();
}

void MainWindow::on_pushButton_clicked()
{
    if (!serialPort){
        statusBar()->showMessage(QStringLiteral("串口不存在"), 5000);
        return;
    }
    statusBar()->clearMessage();

    QString comPortName = ui->combo_uart->currentText();
    int Baud = ui->combo_baud->currentText().toInt();

    serialPort->setPortName(comPortName);
    serialPort->setBaudRate(Baud);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if(button_status == false)
    {
        if(serialPort->open(QSerialPort::ReadWrite) == true)
        {
            button_status = true;
            ui->combo_uart->setDisabled(true);
            ui->combo_baud->setDisabled(true);
            ui->pushButton->setText(QStringLiteral("关闭串口"));
            //             connect(serialPort,SIGNAL(readyRead()),this,SLOT(SerialRecvMsgEvent()));
            //QObject::connect(serialPort, &QSerialPort::readyRead, this, &MainWindow::SerialRecvMsgEvent);
        }
        else
        {
            ui->statusBar->showMessage(QStringLiteral("串口打开失败!"),5000);
        }
    }
    else
    {
        button_status = false;
        serialPort->close();
        ui->combo_uart->setEnabled(true);
        ui->combo_baud->setEnabled(true);
        ui->pushButton->setText(QStringLiteral("打开串口"));
    }
}
